const express=require('express');
const app=express();
const path = require('path');

var db=require('./model/dao.js');
// var mydate=require('./modal/formatDate.js')
//ejs
const ejs=require('ejs');
app.set('view engine','ejs');

//post
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

//md5加密
const md5 = require('md5');
//cookie
var cookieParser=require('cookie-parser')
app.use(cookieParser())

// session
var session = require('express-session')
// 持久化
var NedbStore = require('nedb-session-store')( session );
app.use(session({
	secret: 'keyboard cat',
	resave: false,
	saveUninitialized: true,
	cookie:{
		maxAge:1000*60*60
	},
// 配置持久化
  	store: new NedbStore({
      	filename: 'path_to_nedb_persistence_file.db'
	})
}))

// 转化id格式
const ObjectId = require('mongodb').ObjectId;

//聊天室
const http=require('http').Server(app);
const io=require('socket.io')(http)

//加载静态资源
app.use('/public',express.static('./public/'));
// app.use(express.static(path.join(__dirname, 'public')))

//主页面
app.get('/',(req,res)=>{
	var m=0;
	if(req.session.login){
		db.find('weibo','info',{},(result)=>{
			res.render('index',{mess:result,user:req.session.user,login:true});
		},{_id:-1},m,5)
	}else{
		db.find('weibo','info',{},(result)=>{
			res.render('index',{mess:result,user:'',login:false})
		},{_id:-1},m,5)
	}
})

//注册页面
app.get('/register',(req,res)=>{
    res.render('register');
})

//登录页面
app.get(`/login`,(req,res)=>{
	if(req.session.login){
		res.redirect('http://localhost:3000/');
	}else{
		res.render('login');
	}
})

//退出登录
app.get(`/quit`,(req,res)=>{
	delete req.session.user;
	delete req.session.login;
	res.redirect('http://localhost:3000/')
})
//用户注册
app.post(`/register`,urlencodedParser,(req,res)=>{
	var password=req.body.password;
	if(password!=''&&password!=undefined){
		password=md5(md5(password));
	}
	var str={
		"username":req.body.username,
		"password":password
		// mytime:req.body.mytime,
	}
	db.find('weibo','user',{'username':str.username},(result)=>{
		if(result.length==0){
			//判断是否是提交按钮 
			if(str.password){
				db.insert('weibo','user',str,res,()=>{
					res.send({"status":"数据插入成功！"});
				})
			}else{
				res.send({"status":"ok"})
			}
		}else{
			res.send({"status":"用户名已经存在"})
		}
	})
})

//用户登录
app.post(`/login`,urlencodedParser,(req,res)=>{
	var str={
		'username':req.body.username,
		'password':md5(md5(req.body.password)),
	}
	db.find('weibo','user',{'username':str.username},(result)=>{
		if(result.length==0){
			res.send({"status":"账号错误"})
		}else{
			if(str.password!=result[0].password){
				res.send({"status":"密码错误"})
			}else{
				req.session.user=str.username;
				req.session.login=true;
				res.send({"status":"登录成功"})
			}
		}	
	})
})

//保存微博
app.post(`/weibo`,urlencodedParser,(req,res)=>{
	var date=new Date()
	var gettime=date.getTime()
	var str={
		'username':req.body.username,
		'time':gettime,
		'weibo':req.body.weibo,
		'love':{}
	}
	db.insert('weibo','info',str,res,(result)=>{
		db.find('weibo','info',{},(result)=>{
			res.send({"status":"数据插入成功！",mess:result,'time':str.time});
		},{_id:-1},0,5)
		// res.send({"status":"数据插入成功！",'time':str.time});
	})
})

//保存评论
app.post(`/comment`,urlencodedParser,(req,res)=>{
	var date=new Date()
	var gettime=date.getTime()
	var str={
		'username':req.body.username,
		'time':gettime,
		'weibo':req.body.weibo
	}
	// var id=ObjectId(req.body.id)
	var uid=req.body.id
	db.insert('weibo','comment',{uid:uid,mess:str},res,(result)=>{
		res.send({"status":"评论插入成功！",'time':str.time});
	})
})

//获取评论
app.post(`/getcomment`,urlencodedParser,(req,res)=>{
	var uid=req.body.uid;
	var m=req.body.m
	var n=req.body.n
	db.find('weibo','comment',{uid:uid},(result)=>{
		res.send(result)
	},{_id:-1},m,n)
})

//获取微博
app.get('/getweibo',(req,res)=>{
	var m=req.query.m;
	var n=req.query.n;
	var time=new Date()
	if(n!=undefined){
		db.find('weibo','info',{},(result)=>{
			res.send({mess:result,times:time});
		},{_id:-1},m,n)
	}else{
		db.find('weibo','info',{},(result)=>{
			res.send({mess:result,times:time});
		},{_id:-1},m)
	}
})

//点赞
app.post('/dianzan',urlencodedParser,(req,res)=>{
	var username=req.body.username;
	var uid=ObjectId(req.body.uid);
	var getlove=req.body.getlove;
	var login=req.body.login;
	db.find('weibo','info',{_id:uid},(result)=>{
		if(getlove==1){
			if(login!='true'){
				res.send({'len':Object.keys(result[0].love).length,'love':0})
			}else{
				if(result[0].love[username]!=undefined){
					res.send({'len':Object.keys(result[0].love).length,'love':1})
				}else{
					res.send({'len':Object.keys(result[0].love).length,'love':0})
				}	
			}
		}else{
			if(result[0].love[username]==undefined){
				var mylove=result[0].love
				mylove[username]='1'
				db.update('weibo','info',{_id:uid},{_id:uid,'love':mylove},res,()=>{
					res.send({'len':Object.keys(mylove).length,'love':1})
				})
			}else{
				var mylove=result[0].love
				delete mylove[username]
				db.update('weibo','info',{_id:uid},{_id:uid,'love':mylove},res,()=>{
					res.send({'len':Object.keys(mylove).length,'love':0})
				})
			}
		}
	})
})

//修改密码
app.get('/updatepassword',(req,res)=>{
	res.render('updatepassword');
})
app.post('/updatepassword',urlencodedParser,(req,res)=>{
	var str={
		'username':req.body.username,
		'password':md5(md5(req.body.password)),
		'newpassword':md5(md5(req.body.newpassword)),
	}
	db.find('weibo','user',{'username':str.username},(result)=>{
		if(result.length==0){
			res.send({"status":"账号错误"})
		}else{
			if(str.password!=result[0].password){
				res.send({"status":"密码错误"})
			}else{
				db.update('weibo','user',{'username':str.username,'password':str.password},{'username':str.username,'password':str.newpassword},res,(result)=>{
					delete req.session.user;
					delete req.session.login;
					res.send({'a':'修改密码成功','b':result})
				})	
			}
		}	
	})
})

//聊天室
app.get('/chatroom',(req,res)=>{
	if(req.session.login==true){
		res.render('chatroom',{user:req.session.user})
	}else{
		res.render('login');
	}
})
var users={};
io.on('connection',(socket)=>{
	console.log('connect.....');
	socket.on('login',(msg)=>{
		users[msg.uid]=1
		io.emit('login',{len:Object.keys(users).length,uid:msg.uid,user:users})
	})
	
	socket.on('chat',(msg)=>{
		// db.insert('weibo','chat',{uid:msg.uid,msg:msg.info,time:gettime},res,(result)=>{
		// 	res.send({"status":"发言成功！",'time':gettime});
		// })
		var date=new Date();
		var gettime=date.getTime();
		io.emit('send',{uid:msg.uid,msg:msg.info,time:gettime})
	})
	socket.on('exit',(msg)=>{
		var myuid=msg.uid
		console.log(users[myuid])
		delete users[myuid]
		io.emit('exit',{len:Object.keys(users).length,uid:msg.uid,user:users})
		console.log(users)
	})
})



//服务器
// app.listen('3000',()=>{
//     console.log('成功')
// })

http.listen(3000)